import React, { useState, useEffect } from 'react';
import { DatePicker, Row, Col, Card, Button, Space, Typography } from 'antd';
import { SwapOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

const { Text } = Typography;

// 时分秒轮播选择器组件
const TimeWheelPicker = ({ value, onChange, placeholder }) => {
    const [hour, setHour] = useState(value ? dayjs(value).hour() : 0);
    const [minute, setMinute] = useState(value ? dayjs(value).minute() : 0);
    const [second, setSecond] = useState(value ? dayjs(value).second() : 0);

    // 生成选项数组
    const generateOptions = (max, step = 1) => {
        const options = [];
        for (let i = 0; i < max; i += step) {
            options.push(i.toString().padStart(2, '0'));
        }
        return options;
    };

    const hours = generateOptions(24);
    const minutes = generateOptions(60);
    const seconds = generateOptions(60);

    // 更新时间
    const updateTime = (newHour = hour, newMinute = minute, newSecond = second) => {
        const date = value ? dayjs(value) : dayjs();
        const newTime = date.hour(newHour).minute(newMinute).second(newSecond);
        onChange?.(newTime);
    };

    useEffect(() => {
        if (value) {
            setHour(dayjs(value).hour());
            setMinute(dayjs(value).minute());
            setSecond(dayjs(value).second());
        }
    }, [value]);

    const wheelStyle = {
        height: '120px',
        overflowY: 'auto',
        border: '1px solid #d9d9d9',
        borderRadius: '6px',
        background: '#fff',
        textAlign: 'center',
        WebkitOverflowScrolling: 'touch', // iOS平滑滚动
    };

    const optionStyle = {
        padding: '8px 0',
        fontSize: '16px',
        cursor: 'pointer',
        transition: 'all 0.2s',
        borderBottom: '1px solid #f0f0f0',
    };

    const selectedStyle = {
        ...optionStyle,
        backgroundColor: '#1890ff',
        color: '#fff',
        fontWeight: 'bold',
    };

    return (
        <Card
            size="small"
            title={placeholder || "选择时间"}
            style={{ margin: '8px 0' }}
        >
            <Row gutter={[8, 0]} align="middle">
                <Col span={7}>
                    <Text strong style={{ fontSize: '12px', color: '#666' }}>时</Text>
                    <div style={wheelStyle} className="mobile-time-picker-wheel">
                        {hours.map((h, index) => (
                            <div
                                key={h}
                                style={parseInt(h) === hour ? selectedStyle : optionStyle}
                                className={parseInt(h) === hour ? 'mobile-time-picker-selected' : ''}
                                onClick={() => {
                                    setHour(parseInt(h));
                                    updateTime(parseInt(h), minute, second);
                                }}
                            >
                                {h}
                            </div>
                        ))}
                    </div>
                </Col>

                <Col span={1} style={{ textAlign: 'center' }}>
                    <Text style={{ fontSize: '18px', fontWeight: 'bold' }}>:</Text>
                </Col>

                <Col span={7}>
                    <Text strong style={{ fontSize: '12px', color: '#666' }}>分</Text>
                    <div style={wheelStyle} className="mobile-time-picker-wheel">
                        {minutes.map((m, index) => (
                            <div
                                key={m}
                                style={parseInt(m) === minute ? selectedStyle : optionStyle}
                                onClick={() => {
                                    setMinute(parseInt(m));
                                    updateTime(hour, parseInt(m), second);
                                }}
                            >
                                {m}
                            </div>
                        ))}
                    </div>
                </Col>

                <Col span={1} style={{ textAlign: 'center' }}>
                    <Text style={{ fontSize: '18px', fontWeight: 'bold' }}>:</Text>
                </Col>

                <Col span={7}>
                    <Text strong style={{ fontSize: '12px', color: '#666' }}>秒</Text>
                    <div style={wheelStyle} className="mobile-time-picker-wheel">
                        {seconds.map((s, index) => (
                            <div
                                key={s}
                                style={parseInt(s) === second ? selectedStyle : optionStyle}
                                onClick={() => {
                                    setSecond(parseInt(s));
                                    updateTime(hour, minute, parseInt(s));
                                }}
                            >
                                {s}
                            </div>
                        ))}
                    </div>
                </Col>
            </Row>

            <div style={{ marginTop: '12px', textAlign: 'center' }}>
                <Text style={{ fontSize: '14px', color: '#1890ff', fontWeight: 'bold' }}>
                    {hour.toString().padStart(2, '0')}:
                    {minute.toString().padStart(2, '0')}:
                    {second.toString().padStart(2, '0')}
                </Text>
            </div>
        </Card>
    );
};

// 移动端时间范围选择器主组件
const MobileTimeRangePicker = ({ value, onChange, placeholder = ['开始时间', '结束时间'] }) => {
    const [startDate, setStartDate] = useState(value?.[0] ? dayjs(value[0]).startOf('day') : null);
    const [endDate, setEndDate] = useState(value?.[1] ? dayjs(value[1]).startOf('day') : null);
    const [startTime, setStartTime] = useState(value?.[0] || null);
    const [endTime, setEndTime] = useState(value?.[1] || null);

    // 更新最终值
    const updateValue = (newStartDate = startDate, newEndDate = endDate, newStartTime = startTime, newEndTime = endTime) => {
        if (newStartDate && newStartTime) {
            const start = newStartDate
                .hour(dayjs(newStartTime).hour())
                .minute(dayjs(newStartTime).minute())
                .second(dayjs(newStartTime).second());

            let end = null;
            if (newEndDate && newEndTime) {
                end = newEndDate
                    .hour(dayjs(newEndTime).hour())
                    .minute(dayjs(newEndTime).minute())
                    .second(dayjs(newEndTime).second());
            }

            onChange?.([start, end]);
        } else {
            onChange?.(null);
        }
    };

    // 初始化时间
    useEffect(() => {
        if (value?.[0]) {
            const start = dayjs(value[0]);
            setStartDate(start.startOf('day'));
            setStartTime(start);
        }
        if (value?.[1]) {
            const end = dayjs(value[1]);
            setEndDate(end.startOf('day'));
            setEndTime(end);
        }
    }, [value]);

    return (
        <div style={{ width: '100%' }}>
            {/* 日期选择 */}
            <Row gutter={[8, 8]}>
                <Col span={12}>
                    <Text strong style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>
                        开始日期
                    </Text>
                    <DatePicker
                        value={startDate}
                        onChange={(date) => {
                            setStartDate(date);
                            if (date) {
                                const newStartTime = startTime || date.hour(0).minute(0).second(0);
                                setStartTime(newStartTime);
                                updateValue(date, endDate, newStartTime, endTime);
                            }
                        }}
                        placeholder={placeholder[0]}
                        style={{ width: '100%' }}
                        size="small"
                        format="YYYY-MM-DD"
                    />
                </Col>

                <Col span={12}>
                    <Text strong style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>
                        结束日期
                    </Text>
                    <DatePicker
                        value={endDate}
                        onChange={(date) => {
                            setEndDate(date);
                            if (date) {
                                const newEndTime = endTime || date.hour(23).minute(59).second(59);
                                setEndTime(newEndTime);
                                updateValue(startDate, date, startTime, newEndTime);
                            }
                        }}
                        placeholder={placeholder[1]}
                        style={{ width: '100%' }}
                        size="small"
                        format="YYYY-MM-DD"
                        disabledDate={(current) => startDate && current && current.isBefore(startDate, 'day')}
                    />
                </Col>
            </Row>

            {/* 时间选择 */}
            {startDate && (
                <TimeWheelPicker
                    value={startTime}
                    onChange={(time) => {
                        setStartTime(time);
                        updateValue(startDate, endDate, time, endTime);
                    }}
                    placeholder="开始时间"
                />
            )}

            {endDate && (
                <TimeWheelPicker
                    value={endTime}
                    onChange={(time) => {
                        setEndTime(time);
                        updateValue(startDate, endDate, startTime, time);
                    }}
                    placeholder="结束时间"
                />
            )}

            {/* 显示选择结果 */}
            {startTime && endTime && (
                <Card size="small" style={{ marginTop: '8px', backgroundColor: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <div style={{ textAlign: 'center' }}>
                        <Text strong style={{ color: '#52c41a' }}>
                            {dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')}
                        </Text>
                        <div style={{ margin: '4px 0' }}>
                            <SwapOutlined style={{ color: '#52c41a' }} />
                        </div>
                        <Text strong style={{ color: '#52c41a' }}>
                            {dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')}
                        </Text>
                    </div>
                </Card>
            )}

            {/* 快捷选择 */}
            <div style={{ marginTop: '12px' }}>
                <Text strong style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '8px' }}>
                    快捷选择
                </Text>
                <Space size="small" wrap>
                    <Button
                        size="small"
                        className="mobile-time-picker-quick-btn"
                        onClick={() => {
                            const now = dayjs();
                            const start = now.startOf('day');
                            const end = now.endOf('day');
                            setStartDate(start);
                            setEndDate(end);
                            setStartTime(start);
                            setEndTime(end);
                            onChange?.([start, end]);
                        }}
                    >
                        今天
                    </Button>
                    <Button
                        size="small"
                        className="mobile-time-picker-quick-btn"
                        onClick={() => {
                            const now = dayjs();
                            const start = now.subtract(1, 'day').startOf('day');
                            const end = now.subtract(1, 'day').endOf('day');
                            setStartDate(start);
                            setEndDate(end);
                            setStartTime(start);
                            setEndTime(end);
                            onChange?.([start, end]);
                        }}
                    >
                        昨天
                    </Button>
                    <Button
                        size="small"
                        className="mobile-time-picker-quick-btn"
                        onClick={() => {
                            const now = dayjs();
                            const start = now.subtract(7, 'day').startOf('day');
                            const end = now.endOf('day');
                            setStartDate(start);
                            setEndDate(end);
                            setStartTime(start);
                            setEndTime(end);
                            onChange?.([start, end]);
                        }}
                    >
                        最近7天
                    </Button>
                </Space>
            </div>
        </div>
    );
};

export default MobileTimeRangePicker;
